const {InternalOAuthError} = require('passport-oauth2');
const OAuth2Strategy = require('passport-oauth2').Strategy;
const APIError = require('./errors/apierror');
const Profile = require('./profile');

class Strategy extends OAuth2Strategy {
    constructor(options, verify) {
        options = options || {};
        options.authorizationURL = options.authorizationURL || 'https://gitee.com/oauth/authorize';
        options.tokenURL = options.tokenURL || 'https://gitee.com/oauth/token';
        options.scopeSeperator = options.scopeSeperator || ' ';
        options.customHeaders = options.customHeaders || {};

        if (!options.customHeaders['User-Agent']) {
            options.customHeaders['User-Agent'] = options.userAgent || 'passport-gitee';
        }

        super(options, verify);

        this.name = 'gitee';
        this._userProfileURL = options.userProfileURL || 'https://gitee.com/api/v5/user';
        this._oauth2.useAuthorizationHeaderforGET(true);
    }

    userProfile(accessToken, done) {
        this._oauth2.get(this._userProfileURL, accessToken, (err, body) => {
            if (err) {
                let json;
                if (err.data) {
                    try {
                        json = JSON.parse(err.data);
                    } catch (e) {
                    }
                }

                if (json && json.message) {
                    return done(new APIError(json.message));
                }
                return done(new InternalOAuthError('Failed to fetch user profile', err));
            }

            let json;
            try {
                json = JSON.parse(body);
            } catch (ex) {
                return done(new Error('Failed to parse user profile'));
            }

            let profile = Profile.parse(json);
            profile.provider = 'gitee';
            profile._raw = body;
            profile._json = json;

            done(null, profile);
        });
    }
}

exports = module.exports = Strategy;
